const app = getApp();

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function iRequest(param) {
  let _this = this;
  wx.request({
    url: app.globalData.requestUrl + param.url || '',
    method: param.method || 'GET',
    data: param.data || '',
    header: app.globalData.header,
    dataType: param.dataType || 'json',
    success: function (res) {
      let ret = res.data;
      if (ret.status === 200) {
        typeof param.success === 'function' && param.success(res);
      }
      else if (ret.status === 1001) {
        console.log("用户未登录，请求重定向至用户登录")
        app.loginUser({
          success: function () {
            console.log('回调执行，数据包:', param)
            _this.request(param)
          }
        })

      } else {
        console.log("================================================================")
        console.log("请求不正确返回")
        console.log('request param：')
        console.log(param)
        console.log('response body')
        console.log(res)

        console.log("================================================================")
        typeof param.success === 'function' && param.success(res);
      }
    },
    fail: function () {
      wx.showToast({
        title: '网络错误',
        icon: 'none',
      })
    }

  })
}

module.exports = {
  formatTime: formatTime,
  request: iRequest
}
